﻿/****************************** Module Header ******************************\
 * Module Name:  ADFS.cs
 * Module Version:  1.0.1 (2012-10-3)
 * Copyright (c) AnyEB.Com (14507247@qq.com)
 * 
 * This class is used to application data file system.
 * 
 * This source is subject to the GPL License.
 * See http://www.gnu.org/licenses/gpl.html.
 * All other rights reserved.
 * 
 * 2013-10-30 by sutroon 1.0.1
 *  1.新增SiteName属性
 *  2.将System、Log、Backup迁移到SiteName目录下,而不是ADF顶级目录下
 * 
 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/
using System;
using System.IO;
using System.Collections.Generic;

namespace UCL.ADF
{
    /// <summary>
    /// 应用程序数据文件
    /// <para>如：</para>
    /// <para>ADFS.Root = Application.StartupPath;</para>
    /// <para>ADFS.SiteName = "SoIM";</para>
    /// <para>ADFS.Instance.Site.SetFileText("AgentID", tbLoginID.Text);</para>
    /// </summary>
    public class ADFS
    {
        /// <summary>
        /// 获取或设置应用程序根路径(末尾无需加\\)
        /// <para>如：ADFS.Root = Application.StartupPath;</para>
        /// <para>系统会自动加上ADF子目录</para>
        /// </summary>
        public static string Root { get; set; }

        /// <summary>
        /// 获取或设置站点名称
        /// <para>如：ADFS.SiteName = "SoERP";</para>
        /// </summary>
        public static string SiteName { get; set; }

        // 私有实例
        private static ADFS instance;

        /// <summary>
        /// 获取或设置ADF实例
        /// </summary>
        public static ADFS Instance
        {
            get
            {
                if (instance == null) instance = new ADFS();
                return instance;
            }
        }

        /// <summary>
        /// 获取或设置Site目录
        /// </summary>
        public ADFS Site { get; set; }

        /// <summary>
        /// 获取或设置Site/System目录
        /// </summary>
        public ADFS System { get; set; }

        /// <summary>
        /// 获取或设置Site/Log目录
        /// </summary>
        public ADFS Log { get; set; }

        /// <summary>
        /// 获取或设置Site/Backup目录
        /// </summary>
        public ADFS Backup { get; set; }

        /// <summary>
        /// Root的补全地址
        /// </summary>
        string rootpath;

        /// <summary>
        /// 实例化ADF对象
        /// </summary>
        public ADFS()
        {
            rootpath = Root + "\\ADF";
            if (string.IsNullOrEmpty(SiteName)) SiteName = "DemoSite";
            this.Site = Directory.Exists(string.Format("{0}\\{1}", rootpath, SiteName)) ? new DirectoryInfo(string.Format("{0}\\{1}", rootpath, SiteName)) : Directory.CreateDirectory(string.Format("{0}\\{1}", rootpath, SiteName));
            this.System = Directory.Exists(string.Format("{0}\\{1}\\System", rootpath, SiteName)) ? new DirectoryInfo(string.Format("{0}\\{1}\\System", rootpath, SiteName)) : Directory.CreateDirectory(string.Format("{0}\\{1}\\System", rootpath, SiteName));
            this.Log = Directory.Exists(string.Format("{0}\\{1}\\Log", rootpath, SiteName)) ? new DirectoryInfo(string.Format("{0}\\{1}\\Log", rootpath, SiteName)) : Directory.CreateDirectory(string.Format("{0}\\{1}\\Log", rootpath, SiteName));
            this.Backup = Directory.Exists(string.Format("{0}\\{1}\\Backup", rootpath, SiteName)) ? new DirectoryInfo(string.Format("{0}\\{1}\\Backup", rootpath, SiteName)) : Directory.CreateDirectory(string.Format("{0}\\{1}\\Backup", rootpath, SiteName));
        }

        /// <summary>
        /// 压缩整个ADF文件夹
        /// </summary>
        public void Zip()
        {
            new FileHelper().ZipFolder(rootpath, string.Format("{0}\\{1}\\Log\\ADF.zip", rootpath, SiteName), new string[] { string.Format("{0}\\{1}\\Log", rootpath, SiteName) });
        }

        /// <summary>
        /// 解压缩还原ADF文件夹
        /// </summary>
        public void UnZip()
        {
            new FileHelper().UnZip(string.Format("{0}\\{1}\\Log\\ADF.zip", rootpath, SiteName), rootpath);
        }

        // 文件夹对象缓存
        private DirectoryInfo cache;

        /// <summary>
        /// 实例化文件夹为ADF对象
        /// </summary>
        /// <param name="di"></param>
        /// <returns></returns>
        public static implicit operator ADFS(DirectoryInfo di)
        {
            return new ADFS(di);
        }

        /// <summary>
        /// 通过文件夹对象实例化ADF对象
        /// </summary>
        /// <param name="di"></param>
        public ADFS(DirectoryInfo di)
        {
            this.cache = di;
        }

        // 子文件夹集合
        private Dictionary<string, ADFS> folders;

        /// <summary>
        /// 获取指定名称的文件夹对象
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ADFS GetFolder(string name)
        {
            if (cache == null) this.cache = Directory.Exists(rootpath) ? new DirectoryInfo(rootpath) : Directory.CreateDirectory(rootpath);
            if (this.folders == null)
            {
                this.folders = new Dictionary<string, ADFS>();
                foreach (DirectoryInfo di in cache.GetDirectories())
                {
                    this.folders.Add(di.Name, di);
                }
            }
            if (this.folders.ContainsKey(name)) return this.folders[name];
            return this.cache.CreateSubdirectory(name);
        }

        /// <summary>
        /// 获取指定名称的文件对象
        /// <para>如：ADFS.Current.GetFolder("AnyEb").GetFolder("Mem01").GetFileText(name);</para>
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetFileText(string name)
        {
            if (!File.Exists(this.cache.FullName + "\\" + name)) File.WriteAllText(this.cache.FullName + "\\" + name, string.Empty);
            return File.ReadAllText(this.cache.FullName + "\\" + name);
        }

        /// <summary>
        /// 获取指定名称的文件对象
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        /// <remarks>2014-2-26 by sutroon</remarks>
        public string GetEncryptFileText(string name)
        {
            if (!File.Exists(this.cache.FullName + "\\" + name)) File.WriteAllText(this.cache.FullName + "\\" + name, string.Empty);
            return EncryptHelper.EncryptTextForFile(File.ReadAllText(this.cache.FullName + "\\" + name), "SUTROON");
        }

        /// <summary>
        /// 获取指定名称的文件行的数组
        /// <para>如：ADFS.Current.GetFolder("AnyEb").GetFolder("Mem01").GetFileLines(name);</para>
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string[] GetFileLines(string name)
        {
            if (!File.Exists(this.cache.FullName + "\\" + name)) File.WriteAllText(this.cache.FullName + "\\" + name, string.Empty);
            return File.ReadAllLines(this.cache.FullName + "\\" + name);
        }

        /// <summary>
        /// 写入指定名称的文件对象
        /// <para>如：ADFS.Current.GetFolder("AnyEb").GetFolder("Mem01").SetFileText(name, content);</para>
        /// </summary>
        /// <param name="name"></param>
        /// <param name="v"></param>
        public void SetFileText(string name, string v, params object[] args)
        {
            if (!File.Exists(this.cache.FullName + "\\" + name)) File.WriteAllText(this.cache.FullName + "\\" + name, string.Empty);
            File.WriteAllText(this.cache.FullName + "\\" + name, string.Format(v, args));
        }

        /// <summary>
        /// 写入指定名称的文件对象
        /// </summary>
        /// <param name="name"></param>
        /// <param name="v"></param>
        /// <param name="args"></param>
        /// <remarks>2014-2-26 by sutroon</remarks>
        public void SetEncryptFileText(string name, string v, params object[] args)
        {
            if (!File.Exists(this.cache.FullName + "\\" + name)) File.WriteAllText(this.cache.FullName + "\\" + name, string.Empty);
            File.WriteAllText(this.cache.FullName + "\\" + name, EncryptHelper.EncryptTextForFile(string.Format(v, args), "SUTROON"));
        }

        /// <summary>
        /// 将文本追加到文件末尾
        /// </summary>
        /// <param name="name"></param>
        /// <param name="v"></param>
        /// <param name="args"></param>
        /// <remarks>2013-11-7 by sutroon</remarks>
        public void AppendFileText(string name, string v, params object[] args)
        {
            if (!File.Exists(this.cache.FullName + "\\" + name)) File.WriteAllText(this.cache.FullName + "\\" + name, string.Empty);
            File.AppendAllText(this.cache.FullName + "\\" + name, string.Format(v, args));
        }

        /// <summary>
        /// 写入日志
        /// <para>日志格式:2013-11-7 16:07:30 Your log text... \n\r</para>
        /// <para>如:ADFS.Instance.Log.WriteLog("", fmt,args);</para>
        /// </summary>
        /// <param name="name">如果名称为空则自动生成文件名,格式 log_2013_11_7_16.log</param>
        /// <param name="fmt"></param>
        /// <param name="args"></param>
        /// <remarks>2013-11-7 by sutroon</remarks>
        public void WriteLog(string name, string fmt, params object[] args)
        {
            if (args.Length > 0) fmt = string.Format(fmt, args);
            fmt = string.Format("{0} {1}{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), fmt, Environment.NewLine);
            // 如果名称为空则自动生成文件名,格式 log_2013_11_7_16.log
            if (string.IsNullOrEmpty(name)) name = string.Format("log_{0}.log", DateTime.Now.ToString("yyyy_MM_dd_HH"));
            AppendFileText(name, fmt);
        }

        /// <summary>
        /// 删除指定名称的文件对象
        /// <para>如：ADFS.Current.GetFolder("AnyEb").GetFolder("Mem01").RemoveFile(name);</para>
        /// </summary>
        /// <param name="name"></param>
        /// <param name="ext"></param>
        public void RemoveFile(string name)
        {
            File.Delete(this.cache.FullName + "\\" + name);
        }

        /// <summary>
        /// 判断指定名称的文件对象是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool ExistsFile(string name)
        {
            return File.Exists(this.cache.FullName + "\\" + name);
        }

        /// <summary>
        /// 返回当前目录的地址,带有后缀
        /// <para>如：ADFS.Current.GetFolder("AnyEb").GetFolder("Mem01").ToString(); 返回 F:\\...\\ADF\\AnyEb\\Mem01</para>
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return cache.FullName;
        }
    }
}
